import 'package:flutter/material.dart';

class NotifierProvider<T extends ChangeNotifier> extends InheritedNotifier<T> {
  const NotifierProvider({
    Key? key,
    required T notifier,
    required Widget child,
  }) : super(key: key, notifier: notifier, child: child);

  static T of<T extends ChangeNotifier>(BuildContext context) {
    // return context.dependOnInheritedWidgetOfExactType<CounterProvider>()!.notifier!;
    // 使用 dependOnInheritedWidgetOfExactType 查找最近的 CounterProvider 实例
    final provider =
        context.dependOnInheritedWidgetOfExactType<NotifierProvider<T>>();
    if (provider == null) {
      throw FlutterError(
        'CounterProvider.of() called with a context that does not contain a CounterProvider of type $T.',
      );
    }
    return provider.notifier!;
  }
}
